package com.weather.pm.fragments;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.li6a209.PullRefreshScrollView;
import com.li6a209.PullRefreshScrollView.OnRefereshListener;
import com.weather.pm.Constants;
import com.weather.pm.R;
import com.weather.pm.WeatherApplication;
import com.weather.pm.activity.HomeActivity;
import com.weather.pm.activity.MyCityListActivity;
import com.weather.pm.activity.WeatherDetailActivity;
import com.weather.pm.beans.City;
import com.weather.pm.beans.Weather;
import com.weather.pm.utils.IconUtils;
import com.weather.pm.utils.UIHelper;
import com.weather.pm.utils.VolleyTool;
import com.weather.pm.utils.VolleyTool.HTTPListener;
import com.weather.pm.views.FlowIndicator;
import com.weather.pm.views.WeatherViewPager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class HomeFragment extends Fragment implements OnClickListener,
HTTPListener {

	private WeatherViewPager mViewPager;
	private RelativeLayout mFragmentLayout;
	private LayoutInflater inflater;
	private TextView mCityName;
	private FlowIndicator mIndicator;
	private ArrayList<Weather> weathers = null;
	HomePagerAdapter pagerAdapter = null;
	ArrayList<View> layouts;
	private boolean isfirst = true;
	private ArrayList<City> myCitys = new ArrayList<City>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		this.inflater = inflater;
		mFragmentLayout = (RelativeLayout) inflater.inflate(
				R.layout.home_fragment, null);
		initView();
		initListener();
		initData();
		return mFragmentLayout;
	}

	// 初始化控�?
	private void initView() {
		Calendar c = Calendar.getInstance();  
		int hour = c.get(Calendar.HOUR_OF_DAY);
		if(hour > 6 && hour < 18){
			mFragmentLayout.setBackgroundResource(R.drawable.bg_day);
		}else{
			mFragmentLayout.setBackgroundResource(R.drawable.bg_night);
		}
		mViewPager = (WeatherViewPager) mFragmentLayout
				.findViewById(R.id.viewPager);
		mCityName = (TextView) mFragmentLayout.findViewById(R.id.cityName);
		mFragmentLayout.findViewById(R.id.imb_add).setOnClickListener(this);
		mIndicator = (FlowIndicator) mFragmentLayout
				.findViewById(R.id.flowIndicator);
	}

	@Override
	public void onResume() {
		super.onResume();

		if (WeatherApplication.getInstance().myCities.size() > 0) {
			layouts = new ArrayList<View>();
			ArrayList<City> cities = WeatherApplication.getInstance().myCities;
			ArrayList<Weather> weathers2 = new ArrayList<Weather>();
			for (City city : cities) {
				weathers2.add(city.weather);
				View layout = createView(city.weather);
				layouts.add(layout);
			}
			weathers = weathers2;
			mIndicator.setCount(weathers.size());
			pagerAdapter = new HomePagerAdapter();
			pagerAdapter.setData(layouts);
			mCityName.setText(weathers.get(0).cityName);
			mViewPager.setAdapter(pagerAdapter);
		}
	}

	// 初始化监�?
	private void initListener() {
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				mIndicator.setSeletion(arg0);
				mCityName.setText(weathers.get(arg0).cityName);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	private void initData() {
		if (isfirst) {
			try {
				myCitys = City.getMyCityList(this.getActivity());
			} finally {
				if (myCitys.size() == 0) {
					Map<String, String> params = new HashMap<String, String>();
					params.put("idList", "7");
					VolleyTool.get(Constants.GET_WEATHER_LIST, params, this,
							Constants.GETWEATHERLIST);
				} else {
					StringBuilder sb = new StringBuilder();
					for (City city : myCitys) {
						sb.append(city.id + ",");
					}
					if (sb.length() != 0) {
						sb.deleteCharAt(sb.length() - 1);

					}
					HashMap<String, String> map = new HashMap<String, String>();
					String s = sb.toString();
					map.put("idList", s);
					VolleyTool.get(Constants.GET_WEATHER_LIST, map, this,
							Constants.GETWEATHERLIST);
				}
			}
		}
	}

	// 主控件的onclick时间
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imb_add:
			Intent intent = new Intent();
			intent.setClass(getActivity(), MyCityListActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	@Override
	public void onResponse(String response, int requestCode) {
		try {

			JSONObject json = new JSONObject(response);
			int status = json.getInt("Status");
			String message = json.getString("Message");

			if (status == 0) {
				weathers = new ArrayList<Weather>();
				// 解析�?��的城市天气信�?
				JSONArray infos = new JSONArray(json.getString("Result"));
				JSONObject obj = null;
				for (int i = 0; i < infos.length(); i++) {
					Weather weather = new Weather();
					Weather.WeatherData data = null;
					Weather.Index index = null;
					obj = infos.getJSONObject(i);
					// 初始化weather实体
					weather.datas = new ArrayList<Weather.WeatherData>();
					weather.indexs = new ArrayList<Weather.Index>();

					// 解析datas数据
					JSONObject cityWeather = obj.getJSONObject("CityWeather");
					JSONArray results = cityWeather.getJSONArray("results");
					JSONObject cityRe = results.getJSONObject(0);
					// 初始化weather的城市数据和pm2.5�?
					weather.cityName = cityRe.getString("currentCity");
					weather.pm25 = cityRe.getString("pm25");
					weather.humidity = cityRe.getString("humidity");

					// 初始化weather中datas数据
					JSONArray dataA = cityRe.getJSONArray("weather_data");
					for (int j = 0; j < dataA.length(); j++) {
						data = weather.new WeatherData();
						JSONObject doo = dataA.getJSONObject(j);
						data.date = doo.getString("date");
						data.weather = doo.getString("weather");
						data.dayPictureUrl = doo.getString("dayPictureUrl");
						data.wind = doo.getString("wind");
						data.temperature = doo.getString("temperature");
						weather.datas.add(data);
					}

					// 初始化weather中index数据
					JSONArray indexA = cityRe.getJSONArray("index");
					for (int j = 0; j < indexA.length(); j++) {
						index = weather.new Index();
						JSONObject io = indexA.getJSONObject(j);
						index.title = io.getString("title");
						index.zs = io.getString("zs");
						index.tipt = io.getString("tipt");
						index.des = io.getString("des");
						weather.indexs.add(index);
					}

					weather.trafficControl = obj.getString("trafficControl");
					weather.lunar = obj.getString("lunar");

					// 获取Pm2.5Model数�?
					Weather.Pm25Model pm25 = weather.new Pm25Model();
					JSONObject pmModel = obj.getJSONObject("Pm25Model");
					pm25.pm25 = pmModel.getString("Pm25");
					pm25.pm10 = pmModel.getString("Pm10");
					pm25.so2 = pmModel.getString("So2");
					pm25.o3 = pmModel.getString("O3");
					pm25.no2 = pmModel.getString("No2");
					pm25.co = pmModel.getString("Co");
					pm25.quality = pmModel.getString("quality");
					pm25.level = pmModel.getString("level");
					pm25.datetime = pmModel.getString("datetime");
					pm25.positionName = pmModel.getString("position_name");
					pm25.aqi = pmModel.getString("aqi");
					weather.pm25Mode = pm25;
					if (myCitys.size() != 0) {
						for (City city : myCitys) {
							if (city.name.equals(weather.cityName)) {
								city.weather = weather;
							}
						}
					}
					weathers.add(weather);
				}
				if(myCitys.size()!=0){
					WeatherApplication.getInstance().myCities = myCitys;
				}else {
					City  city = new City();
					city.id =7;
					city.name = "北京";
					city.weather = weathers.get(0);
					WeatherApplication.getInstance().myCities.add(city);
				}
				// 初始化ViewPager中的各项子View
				layouts = new ArrayList<View>();
				for (int j = 0; j < weathers.size(); j++) {
					View layout = createView(weathers.get(j));
					layouts.add(layout);
				}
				// 动�?设置 2个部分的高度为整屏幕
				mCityName.setText(weathers.get(0).cityName);
				mIndicator.setCount(layouts.size());
				pagerAdapter = new HomePagerAdapter();
				pagerAdapter.setData(layouts);
				mViewPager.setAdapter(pagerAdapter);
				isfirst = false;
			} else {
				if(HomeFragment.this == null)
					Toast.makeText(WeatherApplication.getInstance().getApplicationContext(), message, Toast.LENGTH_LONG).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private View createView(final Weather weather) {
		final PullRefreshScrollView scrollView = new PullRefreshScrollView(
				WeatherApplication.getInstance().getApplicationContext());
		// 加载viewpageritem
		RelativeLayout layout = (RelativeLayout) inflater.inflate(
				R.layout.weather_pager_layout, null);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				UIHelper.getScreenHeight(getActivity())
				- (HomeActivity.bottomLayoutHeight) * 2 - 60);
		// 禁止滚动条效�?
		scrollView.setVerticalScrollBarEnabled(false);
		// 当内容拉到一定程度，继续拉时，系统会出现的阴影效�?
		scrollView.setOverScrollMode(View.OVER_SCROLL_NEVER);
		scrollView.setContentView(layout, params);
		scrollView.hideFootLoading();

		/**
		 * 获取item中的子控件并赋�?
		 * 
		 */
		((ImageView)layout.findViewById(R.id.iconWeather)).setBackgroundResource
		(IconUtils.getIconId(IconUtils.getIconName(weather.datas.get(0).dayPictureUrl))[1]);
		((TextView) layout.findViewById(R.id.temperature))
		.setText(weather.datas.get(0).temperature);
		((TextView) layout.findViewById(R.id.temperatureWord))
		.setText(weather.datas.get(0).weather);
		((TextView) layout.findViewById(R.id.pmText)).setText(weather.pm25Mode.aqi);
		((TextView) layout.findViewById(R.id.limitText)).setText(weather.trafficControl);
		((TextView) layout.findViewById(R.id.windDirection)).setText(weather.datas.get(0).wind);
		((TextView) layout.findViewById(R.id.humidity)).setText(weather.humidity);

		((TextView)layout.findViewById(R.id.date)).setText("©国家环境保护部\n"+weather.datas.get(0).date+"\n农历 "+weather.lunar);
		ImageView iconPm = (ImageView) layout.findViewById(R.id.iconPm);
		int pm25 = Integer.parseInt(weather.pm25Mode.pm25);
		if (pm25 < 50) {
			iconPm.setBackgroundResource(R.drawable.air_level_4);
		} else if (pm25 > 50 && pm25 < 100) {
			iconPm.setBackgroundResource(R.drawable.air_level_2);
		} else if (pm25 > 100 && pm25 < 150) {
			iconPm.setBackgroundResource(R.drawable.air_level_1);
		} else if (pm25 > 150 && pm25 < 200) {
			iconPm.setBackgroundResource(R.drawable.air_level_6);
		} else if (pm25 > 200 && pm25 < 250) {
			iconPm.setBackgroundResource(R.drawable.air_level_7);
		} else if (pm25 > 250 && pm25 < 300) {
			iconPm.setBackgroundResource(R.drawable.air_level_3);
		} else {
			iconPm.setBackgroundResource(R.drawable.air_level_5);
		}

		// 控制scrollview中其他的控件逻辑
		LinearLayout bottomLayout = (LinearLayout) layout
				.findViewById(R.id.bottomLayout);
		bottomLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getActivity(), WeatherDetailActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("weather", weather);
				intent.putExtra("weather", bundle);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.in_from_right,
						R.anim.out_to_left);
			}
		});
		scrollView.setOnRefereshListener(new OnRefereshListener() {
			@Override
			public void onReferesh() {
				/*try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
				scrollView.refreshOver();
			}
		});
		return scrollView;
	}

	// viewpager adapter
	private class HomePagerAdapter extends PagerAdapter {

		private ArrayList<View> lists;

		public void setData(ArrayList<View> lists) {
			this.lists = lists;
		}

		@Override
		public int getCount() {
			return lists.size();
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public Object instantiateItem(View container, int position) {
			((ViewPager) container).addView(lists.get(position));
			return lists.get(position);
		}

	}
}
